package com.example.springbootvalidated.exception;
import com.example.springbootvalidated.enums.ErrorCodeEnum;
import com.example.springbootvalidated.utils.ResultReturn;
import com.example.springbootvalidated.utils.ResultReturnUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolationException;
/**
 * Created by IntelliJ IDEA2022.3.2
 * @Author: Tenghw
 * @Date: 2023/05/05  16:05
 * @Description: 统一异常处理
 */
@Slf4j
@RestControllerAdvice
public class ParamsException {
    @ExceptionHandler({MethodArgumentNotValidException.class})
    //@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "方法参数无效异常")
    @ResponseStatus(code=HttpStatus.BAD_REQUEST)
    public ResultReturn handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        log.warn("<<<<<<进入统一异常MethodArgumentNotValidException处理>>>>>>>");
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder sb = new StringBuilder("校验失败:");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sb.append(fieldError.getField()).append("：").append(fieldError.getDefaultMessage()).append(", ");
        }
        return ResultReturnUtil.fail(ErrorCodeEnum.PARAM_ERROR.getCode(),sb.toString());
    }

    @ExceptionHandler({ConstraintViolationException.class})
    //@ResponseStatus(code=HttpStatus.BAD_REQUEST, reason = "约束违反异常")
    @ResponseStatus(code=HttpStatus.BAD_REQUEST)
    public ResultReturn handleConstraintViolationException(ConstraintViolationException ex) {
        log.warn("<<<<<<进入统一异常ConstraintViolationException处理>>>>>>>");
        return ResultReturnUtil.fail(ErrorCodeEnum.PARAM_ERROR.getCode(),ex.getMessage());
    }
}
